package com.yingxin.yxerp.module.admin;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.commons.helper.PropertiesHelper;
import com.yingxin.yx.framework.encrpty.EncryptConst;
import com.yingxin.yx.framework.encrpty.rsa.RsaDigestsHelper;
import com.yingxin.yx.framework.jwt.TokenSupport;
import com.yingxin.yx.framework.user.core.IUserSupport;
import com.yingxin.yx.framework.user.dto.OnLineUser;
import com.yingxin.yx.framework.user.dto.PermissionDto;
import com.yingxin.yx.framework.user.dto.TokenDto;
import com.yingxin.yx.framework.user.dto.UserDto;
import com.yingxin.yxerp.module.admin.dto.CheckPermissionDto;
import com.yingxin.yxerp.module.permission.vo.req.helper.UserPermissionTreeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fanchao
 */
@Api(tags = "登录用户接口")
@ApiSort(1)
@Validated
@Slf4j
@RestController
@RequestMapping("/u")
public class AccountAuthController {

    @Autowired
    private IUserSupport userSupport;

    @Autowired
    private TokenSupport tokenSupport;

    /**
     * 用户菜单
     * @return
     */
    @ApiOperation("登录用户菜单权限列表")
    @GetMapping("/permissions")
    public List<PermissionDto> listPermissions() {
        UserDto user = userSupport.getUser();
        List<PermissionDto> permissions = user.getPermissions();
        return UserPermissionTreeHelper.buildMenu(permissions);
    }

    /**
     * 获取刷新token
     */
    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/token/refresh", method = RequestMethod.POST)
    @ResponseBody
    public TokenDto refresh(String refreshToken, HttpServletRequest request) {
        if ("OPTIONS".equals(request.getMethod())) {
            return null;
        }
        try {
            return tokenSupport.getRefreshToken(refreshToken);
        } catch (Exception e) {
            throw new BizException("401", "未登录");
        }
    }

    /**
     * 检查用户是否存在某个权限
     */
    @ApiOperation(value = "checkPermission")
    @PostMapping("/checkPermission")
    @ResponseBody
    public CheckPermissionDto checkPermission(@RequestBody CheckPermissionDto dto) {
        dto.setRes(userSupport.hasPermission(dto.getPermission()) ? CommonConst.TRUE : CommonConst.FALSE);
        return dto;
    }

    @ApiOperation(value = "密码公钥加密（接口测试用）")
    @RequestMapping(value = "/rsa", method = RequestMethod.POST)
    @ResponseBody
    public String rsa(String password) {
        String publicKey = PropertiesHelper.getInstance().getProperty(EncryptConst.RSA_PUBLIC_KEY);
        try {
            byte[] encrypted = RsaDigestsHelper.encryptByPublicKey(publicKey, password.getBytes());
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 在线登录
     * @return
     */
    @PostMapping("/loginUserList")
    public Map loginUserList(@RequestBody Map<String, String> query){
        Map<Object, Object> map = new HashMap<>();
        List<OnLineUser> onLineUsers = userSupport.getPCLoginUser(query);
        List<OnLineUser> appLoginUser = userSupport.getAppLoginUser(query);
        map.put("pcUserList",onLineUsers);
        map.put("AppUserList",appLoginUser);
        return map;
    }

    /**
     * 强制退出
     */
    @PostMapping("/loginUserList/forceOut")
    public void forceOut(@RequestBody Map<String, String> map){
        userSupport.forceOutUser(map.get("userId"),map.get("type"));
    }

}